<template>
  <div>
    <div style="margin-top: 10px;display: flex;justify-content: center">
      <el-input v-model="keywords" placeholder="通过用户名搜索用户..." prefix-icon="el-icon-search"
                style="width: 400px;margin-right: 10px" @keydown.enter.native="doSearch"></el-input>
      <el-button icon="el-icon-search" type="primary" @click="doSearch">搜索</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="showAddHrView = true">添加用户</el-button>
    </div>
    <div class="hr-container">
      <el-card v-for="hr in hrs" :key="hr.id" class="hr-card">
        <div slot="header" class="clearfix">
          <span>{{ hr.name }}</span>
          <el-button style="float: right; padding: 3px 0;color: #e30007;" type="text"
                     icon="el-icon-delete" @click="deleteHr(hr)"></el-button>
        </div>
        <div>
          <div class="img-container">
            <img :src="hr.userface" :alt="hr.name" :title="hr.name" class="userface-img">
          </div>
          <div class="userinfo-container">
            <div>用户名：{{ hr.name }}</div>
            <div>手机号码：{{ hr.phone }}</div>
            <div>电话号码：{{ hr.telephone }}</div>
            <div>地址：{{ hr.address }}</div>
            <div>用户状态：
              <el-switch
                  v-model="hr.enabled"
                  active-text="启用"
                  @change="enabledChange(hr)"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  inactive-text="禁用">
              </el-switch>
            </div>
            <div>用户角色：
              <el-tag :type="hr.enabled?'success':'info'" style="margin-right: 4px" v-for="(role,indexj) in hr.roles"
                      :key="indexj">{{ role.nameZh }}
              </el-tag>
              <el-popover
                  placement="right"
                  title="角色列表"
                  @show="showPop(hr)"
                  @hide="hidePop(hr)"
                  width="200"
                  trigger="click">
                <el-select v-model="selectedRoles" multiple placeholder="请选择">
                  <el-option
                      v-for="(r,indexk) in allRoles"
                      :key="indexk"
                      :label="r.nameZh"
                      :value="r.id">
                  </el-option>
                </el-select>
                <el-button slot="reference" icon="el-icon-more" type="text"></el-button>
              </el-popover>
            </div>
            <div>备注：{{ hr.remark }}</div>
          </div>
        </div>
      </el-card>
    </div>
    <div>
      <el-dialog
          title="Hr信息"
          :visible.sync="showAddHrView"
          width="40%"
          :before-close="closeAddHrDialog">
        <el-form :model="hr" :rules="rules" ref="addHrRef">
          <el-form-item prop="name">
            <el-tag>Hr姓名:</el-tag>
            <el-input size="mini" style="width: 400px" prefix-icon="el-icon-edit" v-model="hr.name"
                      placeholder="请输入Hr姓名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-tag>手机号码:</el-tag>
            <el-input size="mini" style="width: 150px" prefix-icon="el-icon-edit" v-model.number="hr.phone"
                      placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <el-form-item prop="telephone">
            <el-tag>电话号码:</el-tag>
            <el-input size="mini" style="width: 150px" prefix-icon="el-icon-edit" v-model.number="hr.telephone"
                      placeholder="请输入电话号码"></el-input>
          </el-form-item>
          <el-form-item prop="remark">
            <el-tag>备注:</el-tag>
            <el-input size="small" style="width: 300px" prefix-icon="el-icon-edit" v-model="hr.remark"
                      type="textarea"
                      placeholder="请输入备注"></el-input>
          </el-form-item>
          <el-form-item prop="address">
            <el-tag>地址:</el-tag>
            <el-input size="mini" style="width: 150px" prefix-icon="el-icon-edit" v-model.number="hr.address"
                      placeholder="请输入地址"></el-input>
          </el-form-item>
          <el-form-item prop="address">
            <el-tag>用户名（注意全英文）:</el-tag>
            <el-input size="mini" style="width: 150px" prefix-icon="el-icon-edit" v-model.number="hr.username"
                      placeholder="请输入用户名"></el-input>
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="showAddHrView = false">取 消</el-button>
    <el-button type="primary" @click="addForm()">确 定</el-button>
  </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: "SysHr",
  data() {
    return {
      keywords: "",
      hrs: [],
      selectedRoles: [],
      allRoles: [],
      showAddHrView: false,
      hr: {
        name: "",
        phone: "",
        telephone: "",
        remark: "",
        address: "",
        username: ""
      },
      rules: {
        name: [{required: true, message: '字段不能为空', trigger: 'blur'}],
        phone: [{required: true, message: '字段不能为空', trigger: 'blur'}],
        telephone: [{required: true, message: '字段不能为空', trigger: 'blur'}],
        remark: [{required: true, message: '字段不能为空', trigger: 'blur'}],
        address: [{required: true, message: '字段不能为空', trigger: 'blur'}],
        username: [{required: true, message: '字段不能为空', trigger: 'blur'}]
      }
    }
  },
  mounted() {
    this.initHrs();
  },
  methods: {
    deleteHr(hr) {
      this.$confirm('此操作将永久删除【' + hr.name + '】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRequest("/system/hr/" + hr.id).then(resp => {
          if (resp) {
            this.initHrs();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    enabledChange(hr) {
      this.putRequest("/system/hr/", hr).then((resp) => {
        if (resp) {
          this.initHrs();
        }
      })
    },
    doSearch() {
      this.initHrs();
    },
    showPop(hr) {
      this.initAllRoles();
      let roles = hr.roles;
      this.selectedRoles = [];
      roles.forEach(r => {
        this.selectedRoles.push(r.id)
      })
    },
    hidePop(hr) {
      let flag = false;
      let roles = [];
      Object.assign(roles, hr.roles);
      if (roles.length != this.selectedRoles.length) {
        flag = true;
      } else {
        for (let i = 0; i < roles.length; i++) {
          for (let j = 0; j < this.selectedRoles.length; j++) {
            if (roles[i].id == this.selectedRoles[j]) {
              roles.splice(i, 1);
              this.selectedRoles.splice(j, 1);
              i--;
              break;
            }
          }
        }
        if (roles.length == 0) flag = false;
      }
      if (flag) {
        let url = "/system/hr/role/?hrId=" + hr.id;
        this.selectedRoles.forEach(rid => {
          url += "&rids=" + rid;
        })
        this.putRequest(url).then(resp => {
          if (resp) {
            this.initHrs();
          }
        });
      }
    },
    initHrs() {
      this.getRequest("/system/hr/?keywords=" + this.keywords).then((resp) => {
        if (resp) {
          this.hrs = resp;
        }
      })
    },
    initAllRoles() {
      this.getRequest("/system/hr/roles").then(resp => {
        if (resp) {
          this.allRoles = resp;
        }
      })
    },
    closeAddHrDialog() {
      this.showAddHrView = false;
      this.hr = {
        name: "",
        phone: "",
        telephone: "",
        remark: "",
        address: "",
        username: ""
      };
      this.resetForm();
    },
    addForm() {
      let re = new RegExp("^[a-zA-Z]+$");
      if (!re.test(this.hr.username)) {
        this.$message.error("角色英文名包含非英文字符");
        return;
      }
      console.log("123");
      this.$refs['addHrRef'].validate(valid => {
        if (valid) {
          this.postRequest("/system/hr/", this.hr).then((resp) => {
            if (resp) {
              this.$message.success("添加成功，默认密码为123，请及时修改");
              this.closeAddHrDialog();
              this.initHrs();
            }
          })
        }
      });

    },
    resetForm() {
      this.$refs['addHrRef'].resetFields();
    }
  }
};
</script>

<style>
.userface-img {
  width: 72px;
  height: 72px;
  border-radius: 72px;
}

.userinfo-container div {
  font-size: 12px;
  color: #409eff;
}

.userinfo-container {
  margin-top: 20px;
}

.hr-container {
  display: flex;
  margin-top: 10px;
  justify-content: space-around;
  flex-wrap: wrap;
}

.img-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.hr-card {
  width: 350px;
  margin-bottom: 20px;
}
</style>